﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Primitive.Threading.Sync
{
     class ThreadsSharingData
    {
        private int m_flag = 0;
        private int m_value = 0;

        //这个方法由一个线程执行
        public void Thread1()
        {
            //注意:以下两行代码可能按照相反的顺序执行
            m_value = 5;
            m_flag = 1;
        }

        //这个方法由另一个线程执行
        public void Thread2()
        {
            //注意:m_value可能在m_flag之前读取
            if (m_flag == 1)
            {
                Console.WriteLine(m_value);
            }
        }
    }


class ThreadsSharingData2
{
    private int m_flag = 0;
    private int m_value = 0;

    //这个方法由一个线程执行
    public void Thread1()
    {
        //注意:在将1写入m_flag之前,必须先将5写入m_value
        m_value = 5;
        Thread.VolatileWrite(ref m_flag, 1);
    }

    //这个方法由另一个线程执行
    public void Thread2()
    {
        //注意:m_value必须在读取了m_flag之后读取
        if (Thread.VolatileRead(ref m_flag) == 1)
        {
            Console.WriteLine(m_value);
        }
    }
}
}
